package com.cheer.ba.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aliyun.common.httpfinal.QupaiHttpFinal;
import com.aliyun.common.utils.StorageUtils;
import com.aliyun.demo.crop.AliyunVideoCrop;
import com.aliyun.demo.recorder.AliyunVideoRecorder;
import com.aliyun.struct.common.ScaleMode;
import com.aliyun.struct.common.VideoQuality;
import com.aliyun.struct.recorder.CameraType;
import com.aliyun.struct.recorder.FlashType;
import com.aliyun.struct.snap.AliyunSnapVideoParam;
import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.aliyun.video.Utils;
import com.cheer.ba.app.App;
import com.cheer.ba.app.oss.OssManager;
import com.cheer.ba.app.oss.UploadPicManager;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.TagModel;
import com.cheer.ba.model.ToJsonModel;
import com.cheer.ba.presenter.impl.CommentPresenter;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.service.LocationService;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.TextViewUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.ShowPopupView;
import com.cheer.ba.widget.flowlayout.EvaluateAdapter;
import com.cheer.ba.widget.flowlayout.FlowTagView;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: hq
 * Email: 834138841@qq.com
 * Comment: 图片发布
 * Date: 2017-07-27 17:37
 */
public class VideoPublishAty extends BaseCommAty implements ShowPopupView.OnItemPopupClick {

    //标签
    @BindView(R.id.id_choose_sign_linear)
    LinearLayout mLinearSign;
    @BindView(R.id.id_article_tagview)
    FlowTagView mTagList;
    private EvaluateAdapter mTagAdp;

    //文字
    @BindView(R.id.id_article_edit)
    EditText mEditText;
    private String mSaveText;
    private String mLength;
    //可输入数量
    @BindView(R.id.id_article_num_txt)
    TextView mTxtNum;

    //视频图片
    @BindView(R.id.id_video_img)
    ImageView mImgVideo;
    @BindView(R.id.id_video_type_img)
    ImageView mImgType;

    //位置
    @BindView(R.id.id_article_location)
    TextView mTxtLocation;
    @BindView(R.id.id_article_switchbtn)
    SwitchButton mSwitchBtn;
    //定位服务
    private LocationService mLocationService;

    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"小视频"};

    //存储tagId
    private String mSaveTagId;
    //存储地址
    private String mSaveLocation;
    //视频上传地址
    private String picJson;
    private String mSaveVideoPath;
    private String mSavePicPath;

    //判断是定位权限还是视频权限 true 视频 false 位置
    private boolean recordAuth;

    private String[] eff_dirs;

    private OilMealPresenter mOilMealPresenter;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //视频上传成功
                case 1:
                    ((CommentPresenter) presenter).publishDynamic(true, mSaveText, mSaveTagId, picJson, "3", mSaveLocation);
                    break;
            }
        }
    };

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_video_publish, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initPresenter() {
        presenter = new CommentPresenter();

        mOilMealPresenter = new OilMealPresenter();
        mOilMealPresenter.attachView(this);
        mOilMealPresenter.setmUpLoadPicManager();
    }

    private void initAssetPath() {
        String path = StorageUtils.getCacheDirectory(aty).getAbsolutePath() + File.separator + Utils.QU_NAME + File.separator;
        eff_dirs = new String[]{
                null,
                path + "filter/chihuang",
                path + "filter/fentao",
                path + "filter/hailan",
                path + "filter/hongrun",
                path + "filter/huibai",
                path + "filter/jingdian",
                path + "filter/maicha",
                path + "filter/nonglie",
                path + "filter/rourou",
                path + "filter/shanyao",
                path + "filter/xianguo",
                path + "filter/xueli",
                path + "filter/yangguang",
                path + "filter/youya",
                path + "filter/zhaoyang"
        };
    }

    @Override
    public void initView() {
        setTitleText("视频发布");
        popupView = new ShowPopupView(aty);
        popupView.setOnItemPopupClick(this);
        mImgVideo.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_addpic_unfocused));
        mImgType.setVisibility(View.GONE);

        //标签
        mTagAdp = new EvaluateAdapter(this);
        mTagList.setAdapter(mTagAdp);
        mTagList.setItemClickListener(new FlowTagView.TagItemClickListener() {
            @Override
            public void itemClick(int position) {
                TagModel e = (TagModel) mTagAdp.getItem(position);
                mSaveTagId = e.uid;
                mTagAdp.setCheckAtPosFalse(position, true);
            }
        });

        //当前位置
        mSwitchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    recordAuth = false;
                    mTxtLocation.setText("正在定位...");
                    checkPermissSdcard();
                } else {
                    mTxtLocation.setText("所在位置");
                    mSaveLocation = "";
                }
            }
        });
        mSwitchBtn.setChecked(true);

        setTitleRight("发布", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mSaveText)) {
                    SVProgressHUD.showInfoWithStatus(aty, "至少说点什么吧");
                    return;
                }
                //发布
                if (StringUtils.isEmpty(mSaveVideoPath)) {
                    //无视频，纯文字
                    ((CommentPresenter) presenter).publishDynamic(true, mSaveText, mSaveTagId, picJson, "1", mSaveLocation);
                } else {
                    handVideoPath();
                }
            }
        });
        EventBus.getDefault().register(this);
        ((CommentPresenter) presenter).getTagList(false, "2");

        initAssetPath();
        recordAuth = true;
        checkPermissCamer();
    }

    @Override
    public void initData() {
        TextViewUtils.setSpannableStyleColor("150/150", 0, 3, mTxtNum, R.color.color_main);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSaveText = s + "";
                int l = 0;
                if (StringUtils.isEmpty(mSaveText)) {
                    l = 150;
                    mLength = "";
                } else {
                    int m = mSaveText.length();
                    if (m <= 150) {
                        l = 150 - m;
                        mLength = mSaveText;
                    } else {
                        l = 0;
                        mEditText.setText(mLength);
                        mEditText.setSelection(mLength.length());
                    }
                }
                TextViewUtils.setSpannableStyleColor(l + "/150", 0, (l + "").length(), mTxtNum, R.color.color_main);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    /**
     * 处理视频发布
     */
    public void handVideoPath() {
//        String uuid = UUID.randomUUID().toString();
//        String OSS_LAST_PATH = "android/" + OssManager.VIDEO + uuid + ".android.mp4";
//        uploader.addFile(mSaveVideoPath, "http://" + OssManager.endpoint, OssManager.bucketName, OSS_LAST_PATH, getVodInfo());
//        uploader.start();
        List<String> mPaths = new ArrayList<String>();
        mPaths.add(mSaveVideoPath);
        mPaths.add(mSavePicPath);
        mOilMealPresenter.uploadPic(mPaths);
    }

    @OnClick({R.id.id_del_video_rela, R.id.id_video_img})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_del_video_rela:
                //删除视频

                break;
            case R.id.id_video_img:
                //浏览视频
                if (StringUtils.isEmpty(mSaveVideoPath)) {
                    //弹出发布界面
                    popupView.showAtLocPop(mRootViewLL, POPUP_ITEMS);
                } else {
                    Intent intent = new Intent(aty, FullScreenAty.class);
                    intent.putExtra(IntentKey.General.KEY_URL, mSaveVideoPath);
                    intent.putExtra(IntentKey.General.KEY_BOOLEAN, false);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.PUBLISH_DYNAMIC)) {
                //发布成功
                SVProgressHUD.showSuccessWithStatus(aty, "发布成功");
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.PUBLISH_DYNAMIC;
                EventBus.getDefault().post(event);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            } else if (TextUtils.equals(tag, ConstantTag.GET_TAGS_SUCCESS)) {
                //获得标签列表
                List<TagModel> tags = (List<TagModel>) t;
                if (null != tags && !tags.isEmpty()) {
                    mLinearSign.setVisibility(View.VISIBLE);
                    mTagAdp.setItems(tags);
                }
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_SUCCESS)) {
                //图片上传成功
                List<UploadPicManager.UploadInfo> resultList = (List<UploadPicManager.UploadInfo>) t;
                handVideoToJson(resultList);
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_FAIL)) {
                //图片上传失败
                SVProgressHUD.showInfoWithStatus(aty, "发布失败，请检查网络");
            }
        }
    }

    /**
     * 处理上传成功的界面
     */
    private void handVideoToJson(List<UploadPicManager.UploadInfo> resultList) {
        List<ToJsonModel> toJsons = new ArrayList<ToJsonModel>();
        for (UploadPicManager.UploadInfo info : resultList) {
            ToJsonModel model = new ToJsonModel();
            model.fileName = "";
            model.serialName = "";
            model.fileType = 1;
            model.fileExt = StringUtils.getPicNameFromPath(info.fileSavePath);
            model.fileSize = 0;
            model.fileUrl = info.fileSavePath;
            model.smallPrefix = "";
            model.mediumPrefix = "";
            model.md5 = "";
            toJsons.add(model);
        }
        picJson = new Gson().toJson(toJsons);
        LogUtils.LogD("图片上传成功----", picJson);
        Message msg = new Message();
        msg.what = 1;
        mHandler.sendMessage(msg);
    }

    //是否初始化视频
    private boolean isInitVideo;

    /**
     * 下载图片
     */
    private void toPhotoGraph() {
        if (!isInitVideo) {
            System.loadLibrary("QuCore-ThirdParty");
            System.loadLibrary("QuCore");
            QupaiHttpFinal.getInstance().initOkHttpFinal();
            isInitVideo = true;
        }
        AliyunSnapVideoParam recordParam = new AliyunSnapVideoParam.Builder()
                //设置录制分辨率，目前支持360p，480p，540p，720p
                .setResulutionMode(AliyunSnapVideoParam.RESOLUTION_720P)
                //设置视频比例，目前支持1:1,3:4,9:16
                .setRatioMode(AliyunSnapVideoParam.RATIO_MODE_1_1)
                .setRecordMode(AliyunSnapVideoParam.RECORD_MODE_PRESS) //设置录制模式，目前支持按录，点录和混合模式
//                .setFilterList(eff_dirs) //设置滤镜地址列表,具体滤镜接口接收的是一个滤镜数组
                .setBeautyLevel(70) //设置美颜度
                .setBeautyStatus(true) //设置美颜开关
                .setCameraType(CameraType.BACK) //设置前后置摄像头
                .setFlashType(FlashType.ON) // 设置闪光灯模式
                .setNeedClip(true) //设置是否需要支持片段录制
                .setMaxDuration(10000) //设置最大录制时长 单位毫秒
                .setMinDuration(3000) //设置最小录制时长 单位毫秒
                .setVideQuality(VideoQuality.PD) //设置视频质量
                .setGop(5) //设置关键帧间隔
                //裁剪参数
//                .setMinVideoDuration(4000)
//                .setMaxVideoDuration(29 * 1000)
//                .setMinCropDuration(3000)
//                .setCropMode(ScaleMode.PS)
//                .setFrameRate(25)
                .build();
        AliyunVideoRecorder.startRecordForResult(aty, IntentCode.General.TAKE_VIDEO, recordParam);
    }

    @Override
    public void OnItemClick(int position, String tag) {
        switch (position) {
            case 0:
                //上传视频
                recordAuth = true;
                checkPermissCamer();
                break;
        }
    }

    /**
     * 检测用户定位权限
     */
    private void checkPermissSdcard() {
        String[] perms = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (!mayRequestPermission(perms)) {
            return;
        }
        getLocation();
    }

    /**
     * 检测用户是否开启视频权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            if (recordAuth) {
                toPhotoGraph();
            } else {
                getLocation();
            }
        }
    }

    /**
     * 获取定位地址
     */
    public void getLocation() {
        mLocationService = ((App) getApplication()).mLocationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocationService.registerListener(mListener);
        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        //定位
        mLocationService.start();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                Address mAddress = location.getAddress();
                mSaveLocation = mAddress.city + mAddress.district + mAddress.street;
                if (mSaveLocation.contains("null")) {
                    mSaveLocation = "";
                    mTxtLocation.setText("定位失败");
                } else {
                    mTxtLocation.setText(mSaveLocation);
                }
            }
            mLocationService.stop();
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };

    @Override
    protected void onStop() {
        //注销监听
        if (null != mLocationService) {
            mLocationService.unregisterListener(mListener);
            //停止定位服务
            mLocationService.stop();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IntentCode.General.TAKE_VIDEO) {
            LogUtils.LogD("视频录制", "进来了");
            if (resultCode == Activity.RESULT_OK && data != null) {
                LogUtils.LogD("视频录制", "数据正常....");
                int type = data.getIntExtra(AliyunVideoRecorder.RESULT_TYPE, 0);
                if (type == AliyunVideoRecorder.RESULT_TYPE_CROP) {
                    String path = data.getStringExtra(AliyunVideoCrop.RESULT_KEY_CROP_PATH);
                    LogUtils.LogD("裁剪路径时长", path + "时长：" + data.getLongExtra(AliyunVideoCrop.RESULT_KEY_DURATION, 0));
                } else if (type == AliyunVideoRecorder.RESULT_TYPE_RECORD) {
                    LogUtils.LogD("录制路径时长", data.getStringExtra(AliyunVideoRecorder.OUTPUT_PATH));
                    mSaveVideoPath = data.getStringExtra(AliyunVideoRecorder.OUTPUT_PATH);
                    if (!StringUtils.isEmpty(mSaveVideoPath)) {
                        Bitmap bitmap = getLocalVideoThumbnail(mSaveVideoPath);
                        if (null != bitmap) {
                            mImgVideo.setImageBitmap(bitmap);
                            File file = ImageUtils.compressBmpToFile(aty, bitmap, 10);
                            mSavePicPath = file.getAbsolutePath();
                            mImgType.setVisibility(View.VISIBLE);
                        } else {
                            mSaveVideoPath = "";
                        }
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                ToastUtil.showToast("取消录制");
            }
        }
    }

    /**
     * 获取本地视频的第一帧
     *
     * @param filePath
     * @return
     */
    public Bitmap getLocalVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        //MediaMetadataRetriever 是android中定义好的一个类，提供了统一
        //的接口，用于从输入的媒体文件中取得帧和元数据；
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据文件路径获取缩略图
            retriever.setDataSource(filePath);
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }
}
